package com.zmh.service.http;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zmh.entity.BookEntity;
import com.zmh.entity.CatalogEntity;
import com.zmh.entity.MailEntity;
import com.zmh.service.book.BookService;
import com.zmh.service.book.CatalogService;
import com.zmh.service.http.utils.HttpAPIService;
import com.zmh.service.http.utils.HttpResult;
import com.zmh.service.msg.MailService;

import lombok.extern.slf4j.Slf4j;

/** 
 * BookLink刷新
 * @author zhoumh
 * @version 创建时间：2018年7月20日 上午11:08:24 
 * @Description 
*/
@Service
@Slf4j
public class BookLinkHttp {
	@Autowired
	private HttpAPIService httpAPIService;
	@Autowired
	private BookService bookService;
	@Autowired
	private CatalogService catalogService;
	@Autowired
	private MailService mailService;
	
	/**
	 * 获取书架更新信息
	 * @return: void
	 * @author: zhoumh
	 * @version: 创建时间：2018年7月23日 下午10:14:10 
	 * @Description:
	 */
	public void getBook() throws Exception{
		// 获取书架信息
		String html = httpAPIService.doGet("https://booklink.me/fav_book.php");
//		log.info(html);
		// 获取书籍列表
		Document doc = Jsoup.parse(isLogin(html));
		//选择书籍所在行
		Elements links = doc.select("tr[bgcolor=#fffff0],tr[bgcolor=#f0f0f0]");
		//遍历书籍，对书籍信息处理
		for (Element element : links) {
			//书籍链接
			String nurl = element.select("a[href^=/book]").select("a[rel=nofollow]").attr("href");
			//如果没有书籍链接，就跳过
			if (StringUtils.isEmpty(nurl)) {
				continue;
			}
			//booklink的书籍id
			String idTemp = element.select("a[href^=/book]").select("a[rel!=nofollow]").attr("href");
			String id = idTemp.substring(idTemp.lastIndexOf("-")+1,idTemp.lastIndexOf("."));
			//书名
			String name = element.select("a[href^=/book]").select("a[rel!=nofollow]").text();
			//最新章节
			String cname = element.select("a[href^=/book]").select("a[rel=nofollow]").text();
			//作者
			String author = element.select("a[href^=/author]").text();
//			log.info(idTemp+"   "+id);
			if (catalogService.isExistsCatalogByName(id, cname)) {
				//如果最新章节信息已存在，循环跳过
				continue;
			}
			//根据booklinkid查询已有书籍信息
			BookEntity book = bookService.getBookByBookLinkId(id);
			//如果书籍不存在，就增加书籍
			if (null==book || StringUtils.isEmpty(book.getUuid())) {
				book = new BookEntity();
				//如果没有查找到书名就增加书籍信息,将booklink的id保存等到备注
				book.setDescription(id);
				book.setAuthor(author);
				book.setName(name);
				if (bookService.addBook(book)==1) {
					log.info("书籍信息添加成功"+name);
				}else{
					log.error("添加书籍信息失败! "+name);
				}
			}
			//章节目录检查
			getCatalog(idTemp);
		}
		log.info("已完成本次booklink刷新。");
	}
	/**
	 * 根据书籍目录地址刷新章节
	 * @return: void
	 * @author: zhoumh
	 * @version: 创建时间：2018年7月23日 下午10:13:51 
	 * @Description:
	 */
	public void getCatalog(String idTemp) throws Exception{
		String id = idTemp.substring(idTemp.lastIndexOf("-")+1,idTemp.lastIndexOf("."));
		//获取书籍信息
		BookEntity book = bookService.getBookByBookLinkId(id);
		//根据书籍ID和章节名查找已保存的最新章节信息
		List<CatalogEntity> clist = catalogService.getAllByBid(book.getUuid());
		Map<String, Object> cmap = new HashMap<>();
		for (int i = 0; i < clist.size(); i++) {
			cmap.put(clist.get(i).getDescription(), clist.get(i));
		}
		//增加成功，获取书籍章节信息
		String html = httpAPIService.doGet("https://booklink.me"+idTemp.replace("book", "catalog"));
		// 获取书籍列表
		Document doc =Jsoup.parse(html);
		//选择所有章节
		Elements links = doc.select("tr[bgcolor=#fffff0],tr[bgcolor=#f0f0f0]");
		//全局章节计数器
		int i = 0; 
		//邮件通知内容
		String content = "";
		for (Element element : links) {
			//章节链接
			String curl = element.select("a[href^=/jump.php?sid]").attr("href");
			//如果没有章节链接，就跳过
			if (curl.length()<1) {
				continue;
			}
			String desc = "";
			if (curl.indexOf("&key")>-1) {
				desc = curl.substring(curl.indexOf("cid=")+4, curl.indexOf("&key"));
			}else {
				desc = curl.substring(curl.indexOf("cid=")+4, curl.lastIndexOf("&="));
			}
			//章节名称
			String cname = element.select("a[href^=/jump.php?sid]").text();
			//判断章节是否已存在
			if (null != cmap.get(desc)) {
				continue;
			}
			CatalogEntity catalog = new CatalogEntity();
			String temp = element.select("font[color=#646464]:containsOwn(字)").text();
			//章节字数
			int count = Integer.parseInt(temp.split("/")[0].substring(0, temp.indexOf("字")));
			//章节更新时间
			String ctime = temp.split("/")[1].trim();
			catalog.setCount(count);
			catalog.setCtime(ctime);
			catalog.setName(cname);
			catalog.setBid(book.getUuid());
			catalog.setDescription(desc);
			//增加章节信息
			if (catalogService.addCatalog(catalog) == 1) {
				i++;
				content = content.concat(book.getName()+" 更新章节 "+cname+" \n");
				log.info("章节添加成功： "+book.getName()+" : "+catalog.getName());
			}
			
		}
		String title = "";
		if (i==1) {
			title = content;
		}else{
			title = book.getName()+"共更新："+i+"章节";
		}
//		log.info(book.getName()+"共更新："+i+"章节");
        mailService.saveMail(new MailEntity("小说更新<zhoumh1985@qq.com>", "zmh1812@qq.com", title, content,"sendSimpleMail"));
	}
	
	/**
	 * 验证是否已登录booklink，如果未登录就执行登陆。
	 * @return: html
	 * @author: zhoumh
	 * @version: 创建时间：2018年7月23日 下午10:12:42 
	 * @Description:
	 */
	private String isLogin(String html) throws Exception{
		//验证是否已登录，这里的验证机制还可以继续优化，现在的方式太粗暴了，性能不高。
		//关于httpclient状态保持，还是要继续研究一下的，现在的用法太粗浅了。
		if (html.indexOf("请登录后使用书架功能")>-1) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("username", "wwwxeb");
			map.put("passwd", "8303523");
			map.put("cookie", "4");
			// 登录
			HttpResult result = httpAPIService.doPost("https://booklink.me/after_login.php",map);
			if (result.getCode()==200&&result.getBody().indexOf("登录成功")>-1) {
				log.info("Booklink登录成功！");
			}
			return httpAPIService.doGet("https://booklink.me/fav_book.php");
		}else{
			return html;
		}
	}
}
